package TCP.TCP5;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//服务器
public class TcpEchoServer {
    private ServerSocket listenSocket = null;
    public TcpEchoServer(int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        //通过线程池来服务多个客户端(循环创建多线程，频繁创建销毁线程，高并发的情况下，负担还是很重的，所以这里使用线程池)
        ExecutorService service = Executors.newCachedThreadPool();
        while(true) {
            //通过调用accept来接受请求，若没有客户端来建立连接就会阻塞等待
            Socket clientSocket = listenSocket.accept();
            //通过线程池来解决频繁创建销毁线程的问题
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    public void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%s] 客户端上线!\n", clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        //处理客户端请求
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while(true) {
                //1.读取请求并解析
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()) {
                    //客户端断开连接的时候，hasNext()就会返回false，所以，客户端一下线就结束该线程
                    System.out.printf("[%s:%s] 客户端下线!\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.将响应写回到服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲数据区，确保确实将数据写入
                printWriter.flush();
                //打印日志
                System.out.printf("[%s:%s] req: %s, resp: %s\n", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //clientSocket在循环中，每来一个客户端就会为他分配一个；
            //对象会反复被new出实例，每创建一个，都要消耗一个文件描述符；
            //因此就要把不需要的clientSocket释放掉
            clientSocket.close();
        }
    }
    //这是一个回显服务器
    public String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}

